<script>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'EmployeeTable',
  setup() {
    // 列定义
    const columns = ref([
      { title: '员工编号', key: 'id', visible: true },
      { title: '员工姓名', key: 'name', visible: true },
      { title: '所属部门', key: 'department', visible: true },
      { title: '入职日期', key: 'joinDate', visible: true },
      { title: '员工状态', key: 'status', visible: true }
    ])

    // 受控可见列 keys
    const visibleKeys = ref(columns.value.filter(col => col.visible).map(col => col.key))

    // 计算可见列详细信息
    const visibleColumns = computed(() => {
      return columns.value.filter(col => visibleKeys.value.includes(col.key))
    })


    // 数据
    const allData = ref([])

    // 搜索文本
    const searchText = ref('')

    // 搜索过滤
    const filteredData = computed(() => {
      if (!searchText.value) return allData.value
      return allData.value.filter(emp =>
        Object.values(emp).some(val => String(val).includes(searchText.value))
      )
    })

    function onSearch() {
      currentPage.value = 1
    }

    // 分页相关
    const pageSize = 10
    const currentPage = ref(1)

    const pagedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize
      return filteredData.value.slice(start, start + pageSize)
    })

    function handlePageChange(page) {
      currentPage.value = page
    }

    // 弹窗控制
    const showColumnModal = ref(false)
    let columnBackup = []

    watch(showColumnModal, (val) => {
      if (val) {
        columnBackup = [...visibleKeys.value]
      }
    })

    function cancelColumnSetting() {
      visibleKeys.value = [...columnBackup]
      showColumnModal.value = false
    }

    function confirmColumnSetting() {
      showColumnModal.value = false
    }

    // 员工信息弹窗相关
    const showEmpModal = ref(false)
    const selectedEmployee = ref(null)

    function handleRowClick(row) {
      selectedEmployee.value = row
      showEmpModal.value = true
    }

    function closeEmpModal() {
      showEmpModal.value = false
      selectedEmployee.value = null
      // 重置编辑状态
      isEditing.value = false
      editForm.value = {}
      photoFile.value = null
      photoUrl.value = ""
      if (editFormRef.value) {
        editFormRef.value.resetFields()
      }
    }

    // 编辑员工信息相关
    const isEditing = ref(false)
    const editForm = ref({})
    const editFormRef = ref(null)
    const departmentList = ref([])
    const roleList = ref([])
    const photoFile = ref(null)
    const photoUrl = ref("")

    // 表单验证规则
    const editRules = {
      name: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
      gender: [{ required: true, message: "员工性别不能为空", trigger: "change" }],
      phone: [
        { required: true, message: "联系方式不能为空", trigger: "blur" },
        { pattern: /^\+?[0-9]{7,15}$/, message: "电话号码格式不正确", trigger: "blur" },
      ],
      email: [
        { required: true, message: "邮箱不能为空", trigger: "blur" },
        { type: "email", message: "邮箱格式不正确", trigger: "blur" },
      ],
      departmentId: [{ required: true, message: "所属部门不能为空", trigger: "change" }],
      roleId: [{ required: true, message: "用户角色不能为空", trigger: "change" }],
      position: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      status: [{ required: true, message: "员工状态不能为空", trigger: "change" }],
      idCard: [
        { required: true, message: "身份证号码不能为空", trigger: "blur" },
        {
          pattern: /^[1-9]\d{5}\d{4}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: "身份证号码格式不正确",
          trigger: "blur",
        },
      ],
    }

    // 获取部门列表
    async function fetchDepartments() {
      try {
        const res = await axios.get("http://127.0.0.1:8080/admin/department/getAll", {
          headers: {
            token: localStorage.getItem("token"),
          },
        });
        const data = res.data;
        if (data.code === 200) {
          departmentList.value = data.data || [];
        } else {
          ElMessage.error(data.message || "获取部门失败");
        }
      } catch (e) {
        ElMessage.error("获取部门失败");
      }
    }

    // 角色映射
    const roleMapping = {
      1: '普通员工',
      2: '考核人员', 
      3: '管理员'
    }

    // 状态映射
    const statusMapping = {
      1: '在职',
      0: '离职'
    }

    // 根据roleMapping生成角色列表
    function generateRoleList() {
      roleList.value = Object.entries(roleMapping).map(([roleId, roleName]) => ({
        roleId: parseInt(roleId),
        roleName: roleName
      }));
      console.log('生成的角色列表:', roleList.value);
    }

    // 开始编辑
    function startEdit() {
      if (!selectedEmployee.value || !selectedEmployee.value.fullInfo) return
      
      const emp = selectedEmployee.value.fullInfo
      console.log('开始编辑员工信息:', emp);
      console.log('当前角色信息:', emp.userRole);
      
      editForm.value = {
        employeeId: emp.employeeId,
        name: emp.name || '',
        gender: emp.gender || '',
        birthDate: emp.birthDate ? emp.birthDate.split(' ')[0] : '',
        phone: emp.phone || '',
        email: emp.email || '',
        departmentId: emp.department ? emp.department.departmentId : null,
        roleId: emp.userRole ? emp.userRole.roleId : null,
        position: emp.position || '',
        status: emp.status || 1,
        idCard: emp.idCard || '',
      }
      
      console.log('编辑表单数据:', editForm.value);
      photoUrl.value = emp.photo || ''
      isEditing.value = true
    }

    // 取消编辑
    function cancelEdit() {
      isEditing.value = false
      editForm.value = {}
      photoFile.value = null
      photoUrl.value = ""
      // 重置表单验证状态
      if (editFormRef.value) {
        editFormRef.value.resetFields()
      }
    }

    // 处理照片上传
    function handlePhotoChange(file) {
      photoFile.value = file.raw;
      const reader = new FileReader();
      reader.onload = (e) => {
        photoUrl.value = e.target.result;
      };
      reader.readAsDataURL(file.raw);
    }

    function handlePhotoRemove() {
      photoFile.value = null;
      photoUrl.value = "";
    }

    // 保存编辑
    async function saveEdit() {
      try {
        await editFormRef.value.validate();
        const formData = new FormData();
        const jsonData = {};
        Object.keys(editForm.value).forEach((key) => {
          if (editForm.value[key] !== null && editForm.value[key] !== "") {
            jsonData[key] = editForm.value[key];
          }
        });
        
        console.log('准备发送给后端的数据:', jsonData);
        console.log('选择的角色ID:', jsonData.roleId);
        console.log('对应的角色名称:', roleMapping[jsonData.roleId]);
        
        formData.append("jsonData", JSON.stringify(jsonData));
        
        if (photoFile.value) {
          formData.append("photo", photoFile.value);
        }
        console.log(formData);
        

        const response = await axios.put(
          "http://127.0.0.1:8080/admin/emp/update",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
              token: localStorage.getItem("token"),
            },
          }
        );
        
        const result = response.data;
        if (result.code === 200) {
          ElMessage.success("员工信息更新成功！");
          isEditing.value = false;
          // 重新获取数据
          allData.value = await fetchEmpData();
        } else {
          ElMessage.error(result.message || "更新失败");
        }
      } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败，请检查网络连接");
      }
    }

    async function fetchEmpData() {
      const res = await axios.get('http://127.0.0.1:8080/admin/emp/getAll', {
        params: {
          pageNum: currentPage.value,
          pageSize: 10
        },
        headers:{
          token: localStorage.getItem("token")
        }
      })
      console.log(res);
      
      // 假设后端返回的数据在 res.data.data
      return res.data.data.map(emp => ({
        id: emp.employeeId,
        name: emp.name,
        department: emp.department ? emp.department.departmentName : '',
        joinDate: emp.hireDate ? emp.hireDate.split(' ')[0] : '',
        status: emp.status === 1 ? '在职' : '离职',
        // 保存完整信息用于弹窗显示，并确保角色信息正确
        fullInfo: {
          ...emp,
          userRole: emp.userRole ? {
            roleId: emp.userRole.roleId,
            roleName: roleMapping[emp.userRole.roleId] || emp.userRole.roleName
          } : null
        }
      }))
    }

    onMounted(async () => {
      allData.value = await fetchEmpData()
      await fetchDepartments()
      generateRoleList()
    })

    return {
      columns,
      visibleKeys,
      visibleColumns,
      allData,
      searchText,
      filteredData,
      onSearch,
      pageSize,
      currentPage,
      pagedData,
      handlePageChange,
      showColumnModal,
      cancelColumnSetting,
      confirmColumnSetting,
      showEmpModal,
      selectedEmployee,
      handleRowClick,
      closeEmpModal,
      // 编辑相关
      isEditing,
      editForm,
      editFormRef,
      editRules,
      departmentList,
      roleList,
      roleMapping,
      statusMapping,
      photoFile,
      photoUrl,
      startEdit,
      cancelEdit,
      saveEdit,
      handlePhotoChange,
      handlePhotoRemove
    }
  }
}
</script>
<template>
  <div class="p-6 bg-white min-h-screen">
    <!-- 工具栏 -->
    <div class="flex justify-between items-center mb-4">
      <el-button type="primary" plain icon="el-icon-setting" @click="showColumnModal = true">
        列设置
      </el-button>

      <el-input
        v-model="searchText"
        placeholder="搜索员工信息"
        prefix-icon="el-icon-search"
        clearable
        @input="onSearch"
        style="width: 320px"
      />
    </div>

    <!-- 表格 -->
    <el-table 
      :data="pagedData" 
      border 
      style="width: 100%"
      @row-click="handleRowClick"
      :row-class-name="'cursor-pointer hover:bg-gray-50'"
    >
      <el-table-column
        v-for="col in visibleColumns"
        :key="col.key"
        :prop="col.key"
        :label="col.title"
        :min-width="100"
      >
        <template #default="scope">
          <span v-if="col.key === 'status'">
            <el-tag
              v-if="scope.row.status === '在职'"
              type="success"
              effect="plain"
            >在职</el-tag>
            <el-tag
              v-else
              type="danger"
              effect="plain"
            >离职</el-tag>
          </span>
          <span v-else>{{ scope.row[col.key] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-between items-center mt-4">
      <div class="text-sm text-gray-600">共 {{ filteredData.length }} 条</div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="filteredData.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 列设置弹窗 -->
    <el-dialog v-model="showColumnModal" title="列设置" width="30%" :close-on-click-modal="false">
      <el-checkbox-group v-model="visibleKeys">
        <el-checkbox
          v-for="col in columns"
          :key="col.key"
          :label="col.key"
        >
          {{ col.title }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="cancelColumnSetting">取消</el-button>
        <el-button type="primary" @click="confirmColumnSetting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 员工信息弹窗 -->
    <el-dialog 
      v-model="showEmpModal" 
      title="员工详细信息" 
      width="70%" 
      :close-on-click-modal="false"
      @close="closeEmpModal"
    >
      <div v-if="selectedEmployee && selectedEmployee.fullInfo" class="space-y-6">
        <!-- 查看模式 -->
        <div v-if="!isEditing">
          <!-- 基本信息 -->
          <div>
            <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">基本信息</h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">员工编号：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.employeeId }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">员工姓名：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.name }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">性别：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.gender }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">出生日期：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.birthDate ? selectedEmployee.fullInfo.birthDate.split(' ')[0] : '未设置' }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">身份证号：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.idCard || '未设置' }}</span>
              </div>
                          <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">员工状态：</span>
              <el-tag
                v-if="selectedEmployee.fullInfo.status === 1"
                type="success"
                effect="plain"
              >{{ statusMapping[selectedEmployee.fullInfo.status] }}</el-tag>
              <el-tag
                v-else
                type="danger"
                effect="plain"
              >{{ statusMapping[selectedEmployee.fullInfo.status] }}</el-tag>
            </div>
            </div>
          </div>

          <!-- 工作信息 -->
          <div>
            <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">工作信息</h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">所属部门：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.department ? selectedEmployee.fullInfo.department.departmentName : '未分配' }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">职位：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.position || '未设置' }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">入职日期：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.hireDate ? selectedEmployee.fullInfo.hireDate.split(' ')[0] : '未设置' }}</span>
              </div>
                          <div class="flex items-center">
              <span class="font-medium text-gray-700 w-24">用户角色：</span>
              <span class="text-gray-900">
                {{ selectedEmployee.fullInfo.userRole ? 
                   roleMapping[selectedEmployee.fullInfo.userRole.roleId] : 
                   '未设置' }}
              </span>
            </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">最后登录：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.lastLoginTime ? selectedEmployee.fullInfo.lastLoginTime.split(' ')[0] : '从未登录' }}</span>
              </div>
            </div>
          </div>

          <!-- 联系信息 -->
          <div>
            <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">联系信息</h3>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">手机号码：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.phone || '未设置' }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-700 w-24">邮箱地址：</span>
                <span class="text-gray-900">{{ selectedEmployee.fullInfo.email || '未设置' }}</span>
              </div>
            </div>
          </div>

          <!-- 头像信息 -->
          <div v-if="selectedEmployee.fullInfo.photo">
            <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">头像信息</h3>
            <div class="flex items-center space-x-6">
              <img :src="selectedEmployee.fullInfo.photo" alt="员工头像" style="width:48px;height:48px;object-fit:cover;border-radius:50%;border:1px solid #e5e7eb;" />
            </div>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div v-else>
          <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
            <!-- 基本信息 -->
            <div class="mb-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">基本信息</h3>
              <div class="grid grid-cols-2 gap-4">
                <el-form-item label="员工编号" prop="employeeId">
                  <el-input v-model="editForm.employeeId" disabled />
                </el-form-item>
                <el-form-item label="员工姓名" prop="name">
                  <el-input v-model="editForm.name" placeholder="请输入员工姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="editForm.gender">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthDate">
                  <el-input
                    v-model="editForm.birthDate"
                    disabled
                    placeholder="出生日期不可修改"
                  />
                </el-form-item>
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="editForm.idCard" placeholder="请输入身份证号码" />
                </el-form-item>
                <el-form-item label="员工状态" prop="status">
                  <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
                    <el-option 
                      v-for="(label, value) in statusMapping" 
                      :key="value"
                      :label="label" 
                      :value="parseInt(value)" 
                    />
                  </el-select>
                </el-form-item>
              </div>
            </div>

            <!-- 工作信息 -->
            <div class="mb-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">工作信息</h3>
              <div class="grid grid-cols-3 gap-4">
                <el-form-item label="所属部门" prop="departmentId">
                  <el-select v-model="editForm.departmentId" placeholder="请选择部门" style="width: 100%">
                    <el-option
                      v-for="dept in departmentList"
                      :key="dept.departmentId"
                      :label="dept.departmentName"
                      :value="dept.departmentId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户角色" prop="roleId">
                  <el-select v-model="editForm.roleId" placeholder="请选择角色" style="width: 100%">
                    <el-option
                      v-for="role in roleList"
                      :key="role.roleId"
                      :label="role.roleName"
                      :value="role.roleId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位" prop="position">
                  <el-input v-model="editForm.position" placeholder="请输入职位" />
                </el-form-item>
              </div>
            </div>

            <!-- 联系信息 -->
            <div class="mb-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">联系信息</h3>
              <div class="grid grid-cols-2 gap-4">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="邮箱地址" prop="email">
                  <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
                </el-form-item>
              </div>
            </div>

            <!-- 头像信息 -->
            <div class="mb-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">头像信息</h3>
              <el-form-item label="员工照片">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handlePhotoChange"
                  :on-remove="handlePhotoRemove"
                  accept="image/*"
                >
                  <img v-if="photoUrl" :src="photoUrl" class="avatar" />
                  <el-icon v-else><Plus /></el-icon>
                  <div v-if="!photoUrl" class="el-upload__text">点击上传</div>
                </el-upload>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <div class="flex justify-end space-x-3">
          <el-button v-if="!isEditing" @click="closeEmpModal">关闭</el-button>
          <el-button v-if="!isEditing" type="primary" @click="startEdit">编辑</el-button>
          <el-button v-if="isEditing" @click="cancelEdit">取消</el-button>
          <el-button v-if="isEditing" type="primary" @click="saveEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 10px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-radio-group {
  display: flex;
  gap: 20px;
}

.el-upload__text {
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}

.el-input.is-disabled .el-input__wrapper {
  background-color: #f5f7fa;
  color: #909399;
}
</style>
